package com.module.app.base

import android.text.TextUtils
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.helper.ErrorCode
import cn.leancloud.LCException
import com.module.base.base.BaseExceptionViewModel
import com.module.base.network.exception.ServerException
import com.module.base.utils.CommonUtils
import com.module.app.R
import com.module.app.bean.ListViewBean
import kotlinx.coroutines.flow.MutableSharedFlow

open class BaseViewModel : BaseExceptionViewModel() {

    /**
     *  双重校验锁式-单例   列表
     */
    val listFlow: MutableSharedFlow<ListViewBean> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }

    /**
     *  双重校验锁式-单例   错误
     */
    val errorFlow: MutableSharedFlow<ServerException> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }


    /**
     *  自定义抛出异常
     */
    override fun getExtendException(e: Throwable): ServerException? {
        val ex: ServerException
        //learnCloud 跟 bmob
        if (e is BmobException) {
            val code = e.errorCode
            ex = ServerException(e, code)
            if (code == ErrorCode.E9016) {
                ex.msg = CommonUtils.getString(R.string.empty_error)
            } else {
                ex.msg =
                    if (TextUtils.isEmpty(ex.message)) CommonUtils.getString(R.string.empty_error) else ex.message
            }
            return ex
        } else if (e is LCException) {
            val code = e.code
            ex = ServerException(e, code)
            if (code == LCException.UNKNOWN) {
                ex.msg = CommonUtils.getString(R.string.error_unknow)
            } else if (code == LCException.TIMEOUT) {
                ex.msg = "请求超时"
            } else {
                ex.msg =
                    if (TextUtils.isEmpty(ex.message)) CommonUtils.getString(R.string.empty_error) else ex.message
            }
            return ex
        }
        return null;
    }


    /**
     *  自定义接口异常
     */
    override fun getExtendException(code: Int): ServerException? {
        return null;
    }
}